package servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import domain.Collection;
import domain.User;
import service.Factory.ServiceFactory;

/**
 * Servlet implementation class CollectionListServlet
 */
@WebServlet("/CollectionListServlet")
public class CollectionListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CollectionListServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		User curUser = (User)session.getAttribute("_user");
		
		if (curUser != null) {
			int page = request.getParameter("page") == null ? 1 : Integer.parseInt(request.getParameter("page"));
			int limit = 5;
			
			try {
				List<Collection> collections = ServiceFactory.getCollectionServiceInstance().findCollectionsByUser(curUser.getId(), page, limit);
				
				request.setAttribute("collections", collections);
				request.setAttribute("_page", page);
				request.setAttribute("hasPrev", page > 1);
				request.setAttribute("hasNext", collections.size() == limit);
				
				request.getRequestDispatcher("/client/CollectionList.jsp").forward(request, response);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				response.sendRedirect(request.getContextPath()+ "/HomeServlet");
			}
		} else {
			response.sendRedirect(request.getContextPath()+ "/HomeServlet");
		}
	}

}
